from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpRequest, Http404,HttpResponseRedirect
from django.template import loader
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone

from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User

from .forms import UploadFileForm, RegisterForm
from .utils import handle_upload_file
from .models import Question, Choice


class BaseMixin(LoginRequiredMixin):
	login_url='/tutorial/login/'
	redirect_field_name = 'redirect_to'


#generic view class to replace function view
class PollIndexView(BaseMixin, generic.ListView):

	template_name = "tutorial/poll/index.html"
	context_object_name = 'latest_question_list'

	def get_queryset(self):
		return Question.objects.filter(publish_date__lte=timezone.now()).order_by('-publish_date')[:5]


class PollDetailView(BaseMixin, generic.DetailView):
	model = Question
	template_name = "tutorial/poll/detail.html"

	def get_queryset(self):
		return Question.objects.filter(publish_date__lte = timezone.now())

class PollResultsView(BaseMixin, generic.DetailView):
	model=Question
	template_name= "tutorial/poll/results.html"


class ProjectIndexView(BaseMixin, generic.ListView):
	
	template_name = "tutorial/project/index.html"
	context_object_name = "projects"




def poll_index(request):
	latest_question_list = Question.objects.order_by('-publish_date')[:5]
	# output = ", ".join([q.content for q in latest_question_list] )

	# template = loader.get_template("tutorial/poll/index.html")
	context = {
		"latest_question_list":latest_question_list,
	}
	# return HttpResponse(template.render(context, request))

	return render(request, "tutorial/poll/index.html", context)

#detail view of some model
def poll_detail(request, question_id):
	# try:
	# 	question = Question.objects.get(pk=question_id)
	# except Question.DoesNotExist:
	# 	raise Http404("Question not exists")

	question = get_object_or_404(Question, pk=question_id)

	# return HttpResponse("You are looking at question %s."%question_id)
	return render(request, "tutorial/poll/detail.html", {'question':question})


def poll_results(request, question_id):
	# response = "You are looking at the results of question %s."
	# return HttpResponse(response % question_id)
	question = get_object_or_404(Question, pk=question_id)
	return render(request, "tutorial/poll/results.html", {'question':question})

def poll_vote(request, question_id):
	question = get_object_or_404(Question, pk=question_id)

	try:
		select_choice = question.choice_set.get(pk=request.POST['choice'])
	except (KeyError, Choice.DoesNotExist):
		return render(request, "tutorial/poll/detail.html",{
		'question':question,
		'error_message':"You did't select a choice.",
		})
	else:
		select_choice.votes += 1
		select_choice.save()
		return HttpResponseRedirect(reverse('poll-results', args=(question.id,)))

		# return HttpResponse("You are voting on question %s." % question_id)

# Create your views here.

def index(request:HttpRequest):

	return render(request, "tutorial/index.html")

def django_index(request):
	return render(request, "tutorial/index.html")

def django_admin(request):
	return render(request, "tutorial/django/admin.html")


def django_view_postion_args(request, *args):
	text = "<p> Recieved the positional arguments: %s</p>"%(str(args))
	return HttpResponse(text)


# a demostration for file upload views
def django_view_upload(request):
	if request.method == "POST":
		form = UploadFileForm(request.POST, request.FILES)
		if form.is_valid():
			handle_upload_file("test.txt", request.FILES['file'])
			return render(request, "tutorial/django/views/upload_file.html", {"msg":"upload file succeed"})
	else:
		form = UploadFileForm()

	return render(request, "tutorial/django/views/upload_file.html", {"form":form})

# a demostration for file download views
def django_view_dowload(request, **kwargs):

	if len(args) == 0:
		return render(request, "tutorial/django/views/download_file.html")

	datas=None
	with open("test.txt", "rb") as f:
		while True:
			data = f.read(1024)
			if not data:
				break;
			if not datas:
				datas = data
			datas += data

	# used to specify response content type
	response=HttpResponse(content=datas, content_type="plain/text")

	# used to specify download file's name
	response['Content-Disposition']='attachment; filename=test.txt'
	return response

def login_view(request:HttpRequest):


	if request.method == "GET":
		return render(request, "tutorial/login.html")

	username = request.POST['username']
	password = request.POST['password']

	user = authenticate(username=username, password=password)

	if user is not None:
		if user.is_active:
			login(request, user)

			return HttpResponseRedirect(reverse("poll-index"))
		else:

			return render(request, "tutorial/login.html",{
				'error_message':"User is disabled"
			})
	else:
		return render(request, "tutorial/login.html",{
			'error_message':"User does not exist"
		})


def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("poll-index"))

def register_view(request):

	if request.method == "GET":
		form = RegisterForm()
		return render(request, "tutorial/register.html", {'form':form})
	elif request.method == "POST":
		form = RegisterForm(request.POST)
		user=form.save(commit=False)
		content = "login: %s, password: %s"%(user.username, user.password)
		User.objects.create_user(user.username, email=user.email, password=user.password)
		return HttpResponse(content)











































#
